import {AuthService} from "../service/auth/auth.service";
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {Injectable} from "@angular/core";
import {ApiUrls} from "../api.urls";
import {catchError} from "rxjs/operators";
import {MatSnackBar} from "@angular/material";
import {Observable, throwError} from "rxjs/index";
import {LoggerService} from "@ngx-toolkit/logger";

@Injectable()
export class RestAuthInterceptor implements HttpInterceptor {

  constructor(
    private authService: AuthService,
    private snackBar: MatSnackBar,
    private logger: LoggerService) {}

  //自动在请求头加上token，并且处理返回中的错误信息
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>  {
    // Get the auth token from the service.
    let request = req;
    if(this.authService.token){
      // Clone the request and replace the original headers with
      // cloned headers, updated with the authorization.
      request = req.clone({
        headers: req.headers.set(ApiUrls.authorizationHeader, this.authService.token)
      });
    }
    //诡异的写法，拦截返回的请求
    return next.handle(request).pipe(
      catchError(error => {
        if (error.error instanceof ErrorEvent) {  //网络错误
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', error.error.message);
        } else {  //http错误
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          // console.error(error);
          // console.error(
          //   `Backend returned code ${error.status}, ` +
          //   `body was: ${error.error}`);
          this.logger.info(error);
          let msg: string;
          if(error.error["errorCode"]){
            switch (error.error["errorCode"]) {
              case -1:
                this.authService.clearAuthInfo();
                msg = error.error["errorMsg"];
                break;
              case 10000:
                msg = "用户名或密码错误";
                break;
              case 10001:
                msg = error.error["errorMsg"];
                break;
              default:
                msg = error.error["errorMsg"];
                break;
            }
          }
          if(!msg){
            if(error.error["status"] == 403){
              msg = "权限不足";
            }else {
              msg = "未知错误";
            }
          }
          this.snackBar.open(msg, error["statusText"], {
            duration: 5000
          });

        }
        // return an observable with a user-facing error message
        return throwError('Something bad happened; please try again later.');
      })
    );
  }
}
